package com.yc.http.d0703;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Tomcat {

    // Servlet 容器
    private static Map<String, HttpServlet> servletMap = new HashMap<>();

    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(80);
        System.out.println("Tomcat服务器启动完成:80");

        /*
         * 初始化Servlet容器
         */
        servletMap.put("/hello.s", new HelloServlet());

        while (true) {
            Socket socket = server.accept();
            new Thread() {
                public void run() {
                    try (
                            InputStream inputStream = socket.getInputStream();
                            OutputStream outputStream = socket.getOutputStream();
                    ) {
                        // 读取请求报文
                        HttpServletRequest request = new HttpServletRequest(inputStream);

                        //  判断请求: 动态or静态or404
                        if (isServlet(request.getRequestURI())) {
                            // 动态请求
                            processServlet(request, outputStream);
                        } else if (isStatic(request.getRequestURI())) {
                            // 静态请求
                            processStatic(request, outputStream);
                        } else {
                            // 404
                            process404(request);
                        }

                       /* outputStream.write("HTTP/1.1 200 OK\n".getBytes(StandardCharsets.UTF_8));
                        outputStream.write("Content-Type:text/html;charset=utf-8\n".getBytes(StandardCharsets.UTF_8));
                        outputStream.write("\n".getBytes(StandardCharsets.UTF_8));
                        outputStream.write("<h1>hello 中国</h1>".getBytes(StandardCharsets.UTF_8));*/
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ServletException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    private static boolean isStatic(String requestURI) {
        // 判断文件是否存在
        String photoRoot = "D:\\Tomcat俄罗斯终结破解版\\webapps\\photo";
        String filepath = photoRoot + requestURI;
        File file = new File(filepath);
        return file.exists();
    }

    /**
     * 返回 404 响应页面
     *
     * @param request
     */
    private static void process404(HttpServletRequest request) {
    }

    /**
     * 处理静态请求
     *
     * @param request
     * @param outputStream
     * @return
     */
    private static void processStatic(HttpServletRequest request, OutputStream outputStream) throws IOException {
        String photoRoot = "D:\\Tomcat俄罗斯终结破解版\\webapps\\photo";
        String filepath = photoRoot + request.getRequestURI();
        String contentType = "Content-Type:text/html;charset=utf-8\n";
        if (filepath.endsWith(".css")) {
            contentType = "Content-Type:text/css;charset=utf-8\n";
        } else if (filepath.endsWith(".js")) {
            contentType = "Content-Type:application/x-javascript;charset=utf-8\n";
        }
        // 实现显示 404 页面显示
        outputStream.write("HTTP/1.1 200 OK\n".getBytes(StandardCharsets.UTF_8));
        outputStream.write(contentType.getBytes(StandardCharsets.UTF_8));
        outputStream.write("\n".getBytes(StandardCharsets.UTF_8));
        try (FileInputStream fos = new FileInputStream(filepath)) {
            byte[] bytes = new byte[1024];
            int count;
            while ((count = fos.read(bytes)) > -1) {
                outputStream.write(bytes, 0, count);
            }
        }
    }

    /**
     * 处理Servlet请求
     *
     * @param request
     */
    private static void processServlet(HttpServletRequest request, OutputStream outputStream) throws ServletException, IOException {
        // 获取servlet 实例
        HttpServlet servlet = servletMap.get(request.getRequestURI());
        HttpServletResponse response = new HttpServletResponse(outputStream);
        servlet.service(request, response);
        if (response.getStatus() == 0) {
            // 设置默认结果码
            response.setStatus(200, "OK");
        }
        if (response.getContentType() == null) {
            response.setContentType("text/html;charset=utf-8");
        }
        // 执行响应方法
        response.flushBuffer();
    }

    /**
     * 判断是否是Servlet请求
     *
     * @param requestURI
     * @return
     */
    private static boolean isServlet(String requestURI) {
        return servletMap.containsKey(requestURI);
    }
}

/**
 * HTTP 请求报文格式
 * 1. 请求头
 * 请求头行:   请求类型(空格)资源路径(空格)协议版本
 * 键: 值   N个参数
 * 空白行
 * 2. 请求体
 * POST 请求才会产生请求体
 * 1. 表单提交
 * 2. AJAX.post 方法
 * <p>
 * <p>
 * 响应报文格式
 * 1. 响应头
 * 响应投行: 协议(空格)结果码(空格)结果码说明
 * 键: 值   N个参数
 * 空行
 * 2. 相应体
 * <p>
 * <p>
 * 根据请求内容给与对应的响应 : Html js ,css jpg
 * 1. 解析请求报文
 * 2. 分析内容, 找到指定的文件
 * 3. 根据请求, 定制响应报文
 * 4. 传回响应报文
 */
